package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.MemberLevelEnum;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.*;
import cn.ztuo.bitrade.vo.BorrowMoneyVO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;

/**
 * @author: Xiazt
 * @date: 2020-04-27 09:52
 */
@Slf4j
//@RestController
//@RequestMapping("borrowMoney")
public class BorrowMoneyController extends BaseController {

    @Autowired
    private BorrowMoneyService borrowMoneyService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private AccessServiceChargeService accessServiceChargeService;

    @RequestMapping("issueBorrow")
    public MessageResult saveOrUpdate(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, BorrowMoney borrowMoney, String jyPassword, String pledgeCoinUnit, HttpServletRequest request) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            // 验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            // 验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");

            if (borrowMoney.getDayRate().compareTo(BigDecimal.ZERO) <= 0){
                FileUtil.writeErrorLog(request.getRemoteAddr(),borrowMoney.getDayRate(),authMember.getId());
                return error("数据异常！");
            }
            if (borrowMoney.getPeriod() <= 0){
                FileUtil.writeErrorLog(request.getRemoteAddr(),new BigDecimal(borrowMoney.getPeriod()),authMember.getId());
                return error("数据异常！");
            }
            if (borrowMoney.getBorrowAmount().compareTo(BigDecimal.ZERO) <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(), borrowMoney.getBorrowAmount(), authMember.getId());
                return error("数据异常！");
            }

            // 计算利息
            BigDecimal dayRate = BigDecimalUtils.div(borrowMoney.getDayRate(), new BigDecimal(100));
            BigDecimal interestDue = BigDecimalUtils.mul(BigDecimalUtils.mul(borrowMoney.getBorrowAmount(), dayRate), borrowMoney.getPeriod());
            if (interestDue.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
            borrowMoney.setInterestDue(interestDue);

            Coin coin = coinService.findByUnit("USDT");
            // 验证手续费
            AccessServiceCharge serviceCharge = accessServiceChargeService.findByCoin(coin);
            BigDecimal chargeRate = BigDecimalUtils.div(serviceCharge.getServiceChange(), new BigDecimal(100));
            BigDecimal charge = BigDecimalUtils.mul(borrowMoney.getBorrowAmount(), chargeRate);
            if (charge.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
            borrowMoney.setServiceCharge(charge);
            MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);
            if (memberWallet.getBalance().compareTo(borrowMoney.getServiceCharge()) < 0) return error("手续费不足！");

            // 计算质押金额
            MessageResult coinRate = getCoinRate(pledgeCoinUnit);
            // 获取汇率
            String closePrice = coinRate.getMessage();
            // 质押金 = 借款金额 / 70% / 汇率
            BigDecimal pledgeMoney = BigDecimalUtils.div(BigDecimalUtils.div(borrowMoney.getBorrowAmount(), new BigDecimal(0.7)), new BigDecimal(closePrice));
            if (pledgeMoney.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
            borrowMoney.setPledgeMoney(pledgeMoney);
            Coin pledgeCoin = coinService.findByUnit(pledgeCoinUnit);
            MemberWallet pledgeMemberWallet = memberWalletService.findByCoinAndMember(pledgeCoin, member);
            if (pledgeMemberWallet.getBalance().compareTo(borrowMoney.getPledgeMoney()) < 0) return error("质押金额不足！");

            // 业务
            borrowMoneyService.saveOrUpdate(authMember.getId(), borrowMoney, memberWallet, pledgeCoinUnit);
            return success();

        } catch (Exception e) {
            e.printStackTrace();
            return error("网络繁忙，请稍后再试！！");
        }

    }

    @RequestMapping("getBorrowMoneyList")
    public MessageResult getBorrowMoneyList(BorrowMoneyVO borrowMoneyVO) {
        return success(borrowMoneyService.getBorrowMoneyList(borrowMoneyVO));
    }

    /**
     * 撤单
     *
     * @param authMember
     * @param id
     * @param jyPassword
     * @return
     */
    @RequestMapping("cancellations")
    public MessageResult cancellations(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, Long id, String jyPassword) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            // 验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            // 验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");
            BorrowMoney borrowMoney = borrowMoneyService.findById(id);
            if (borrowMoney.getStatus() != 0) return error("该借贷已产生交易，不可撤单！");
            borrowMoneyService.cancellations(authMember.getId(), borrowMoney);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("网络繁忙，请稍后再试！！");
        }

    }


    public MessageResult getCoinRate(String unit) {
        try {
            // 获取当前汇率
            String url = "https://api.huobi.pro/market/detail/merged?symbol=" + unit.toLowerCase() + "usdt";
            String resultString = HttpsUtil.doGet(url);
            JSONObject result = JSONObject.parseObject(resultString);
            JSONObject tick = result.getJSONObject("tick");
            BigDecimal closePrice = tick.getBigDecimal("close");
            return success(closePrice.toString());
//            return success("9304.7");
        } catch (Exception e) {
            e.printStackTrace();
            return error("网络繁忙，请稍后再试！！");
        }
    }

}
